package com.lanou3g.demo.base.controller;

import com.lanou3g.demo.base.service.ILoginService;
import com.lanou3g.demo.entity.AdminInfo;
import com.lanou3g.demo.entity.ExAdminInfo;
import com.lanou3g.demo.utils.ValidateCode;
import com.lanou3g.demo.validate.LoginValidate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.RenderedImage;
import java.awt.image.VolatileImage;
import java.io.IOException;
import java.util.Map;

@Controller
@RequestMapping("/admins")
public class LoginController {
    @Autowired
    private ILoginService loginService;

    @RequestMapping("/login")
    public String login() {
        return "/login";
    }

    @RequestMapping("/exit")
    public String exit(HttpSession session) {
        session.removeAttribute("admin");
        session.invalidate();
        return "forward:/admins/login";
    }

    @RequestMapping(value = "/login.do")
    public String loginDo(@Validated(value = {LoginValidate.class}) AdminInfo admin, BindingResult result, Model model, HttpSession session, HttpServletRequest request) {
        if (session != null) {
            if (session.getAttribute("code") != null) {
                String code = request.getParameter("code");
                // 验证验证码
                String sessionCode = session.getAttribute("code").toString();
                if (code != null && !"".equals(code) && sessionCode != null && !"".equals(sessionCode)) {
                    if (!code.equalsIgnoreCase(sessionCode)) {
                        model.addAttribute("codeError", "验证码输入错误");
                        return login();
                    }
                } else {
                    model.addAttribute("codeError", "验证码输入错误");
                    return login();
                }
                if (result.hasErrors()) {
                    model.addAttribute("result", result);
                    return login();
                } else {
                    ExAdminInfo loginUser = loginService.login(admin.getAdminCode(), admin.getPassword());
                    if (loginUser != null) {
                        session.setAttribute("admin", admin);
                        session.setAttribute("userInfo", loginUser);
                        session.setAttribute("id", loginUser.getAdminId());
                        session.setMaxInactiveInterval(30 * 60);
                        return "forward:/index.do";
                    } else {
                        model.addAttribute("error", "账户或者密码有误,请验证后输入");
                    }
                }
                return login();
            }
        } else {
            return login();
        }
        return login();
    }

    @RequestMapping("/getCode")
    public void getCode(HttpServletRequest req, HttpServletResponse resp, HttpSession session) {

        // 调用工具类生成的验证码和验证码图片
        Map<String, Object> codeMap = ValidateCode.generateCodeAndPic();
        // 将四位数字的验证码保存到Session中。
//        HttpSession session = req.getSession();
        session.setAttribute("code", codeMap.get("code").toString());
        // 禁止图像缓存。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", -1);

        resp.setContentType("image/jpeg");

        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos;
        try {
            sos = resp.getOutputStream();
            ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}


